package com.niiwoo.civet.scheduler.mq;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.constant.RabbitConstant;
import com.niiwoo.civet.trade.constant.TradeRedisKey;
import com.niiwoo.civet.trade.dto.request.BatchInvestRequestDTO;
import com.niiwoo.civet.trade.service.invest.AutoInvestDubboService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created by zhangwanli on 2017/11/17.
 */
@Component
public class InvestMessageListener {
    private static final Logger logger = LoggerFactory.getLogger(InvestMessageListener.class);

    @Reference(version = "1.0.0")
    private AutoInvestDubboService autoInvestDubboService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RabbitListener(queues = {RabbitConstant.Queue.AUTO_INVEST_PROJECT}, exclusive = true)
    public void onAutoInvestMessage(Long projectId, Message message, Channel channel) throws IOException {
        logger.info("自动投资===>收到自动投资MQ消息,projectId={}", projectId);
        try {
            autoInvestDubboService.executeAutoInvest(projectId);
        } catch (Exception e) {
//            redisTemplate.opsForZSet().add(TradeRedisKey.AUTO_INVEST_PROJECT_STASH, projectId.toString(), System.currentTimeMillis());
            logger.error("自动投资===>调用trade服务处理自动投资失败,projectId={}", projectId, e);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        logger.info("自动投资===>ack自动投资MQ消息,projectId={}", projectId);
    }

    @RabbitListener(queues = {RabbitConstant.Queue.BATCH_INVESTOR}, exclusive = true)
    public void onBatchInvestMessage(BatchInvestRequestDTO dto, Message message, Channel channel) throws IOException {
        String userId = dto.getUserId();
        logger.info("批量投资===>收到批量投资MQ消息,userId={}", userId);
        try {
            autoInvestDubboService.executeBatchInvest(dto);
        } catch (Exception e) {
            logger.error("批量投资===>调用trade服务处理批量投资失败,userId={}", userId, e);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        logger.info("批量投资===>ack批量投资MQ消息,userId={}", userId);
    }

}
